import { ref } from 'vue';
import callBaiduAPI from './BaiduTrans';

// Define translation group configuration interface
interface TranslationGroupConfig {
  sourceField: 'english' | 'chinese'; // Source language field
  targetField: 'english' | 'chinese'; // Target language field
  sourceSelector: string; // CSS selector for source input element
  targetSelector: string; // CSS selector for target input element
  index: number; // Group index
  twoWay?: boolean; // Whether to enable two-way translation (optional)
  // 添加缓存字段，用于存储上一次翻译的内容
  lastSourceText?: string;
  lastTargetText?: string;
}

// Store translation groups
const translationGroups = ref<TranslationGroupConfig[]>([]);

// 添加一个翻译队列及其处理状态
const translationQueue: Array<{groupIndex: number, isReverse: boolean, timestamp: number}> = [];
let isProcessingQueue = false;

// 添加一个输入延迟处理机制
const inputDelays: Record<number, ReturnType<typeof setTimeout>> = {};

// 处理翻译队列的函数
async function processTranslationQueue() {
  if (isProcessingQueue || translationQueue.length === 0) return;
  
  isProcessingQueue = true;
  
  // 获取并移除队列中的第一个翻译请求
  const request = translationQueue.shift();
  if (request) {
    console.log(`从队列处理翻译请求: 索引=${request.groupIndex}, 反向=${request.isReverse}, 队列中剩余${translationQueue.length}个请求`);
    
    const group = translationGroups.value.find(g => g.index === request.groupIndex);
    if (group) {
      try {
        // 执行翻译并等待完成
        await executeTranslation(group, request.isReverse);
      } catch (error) {
        console.error('Queue translation error:', error);
      }
    }
    
    // 添加小延迟，避免请求过快
    await new Promise(resolve => setTimeout(resolve, 200));
  }
  
  isProcessingQueue = false;
  
  // 继续处理队列中的下一个请求
  if (translationQueue.length > 0) {
    processTranslationQueue();
  }
}

// 添加请求到翻译队列，但增加延迟机制
function queueTranslation(groupIndex: number, isReverse = false, delayMs = 1000) {
  // 清除之前的定时器（如果存在）
  if (inputDelays[groupIndex]) {
    clearTimeout(inputDelays[groupIndex]);
  }
  
  // 设置新的定时器，延迟添加到队列
  inputDelays[groupIndex] = setTimeout(() => {
    // 检查队列中是否已有相同的请求
    const isDuplicate = translationQueue.some(
      req => req.groupIndex === groupIndex && req.isReverse === isReverse
    );
    
    if (!isDuplicate) {
      // 添加到队列
      translationQueue.push({
        groupIndex,
        isReverse,
        timestamp: Date.now()
      });
      
      console.log(`翻译请求添加到队列: 索引=${groupIndex}, 反向=${isReverse}, 队列长度=${translationQueue.length}`);
      
      // 如果队列没有在处理中，启动处理
      if (!isProcessingQueue) {
        processTranslationQueue();
      }
    } else {
      console.log(`跳过重复的翻译请求: 索引=${groupIndex}, 反向=${isReverse}`);
    }
  }, delayMs);
}

// 直接执行翻译（不经过防抖和队列）
async function executeTranslation(config: TranslationGroupConfig, isReverse = false) {
  try {
    // Get source and target elements
    const sourceElement = document.querySelector(
      isReverse ? config.targetSelector : config.sourceSelector
    ) as HTMLElement;
    
    const targetElement = document.querySelector(
      isReverse ? config.sourceSelector : config.targetSelector
    ) as HTMLElement;
    
    if (!sourceElement || !targetElement) {
      console.error('Translation elements not found:', config);
      return;
    }
    
    // Get text to translate
    const text = sourceElement.innerText || sourceElement.textContent || '';
    if (!text.trim()) {
      // If source is empty, clear target as well
      targetElement.innerText = '';
      return;
    }
    
    // 检查是否与上一次翻译的源文本相同
    const lastSourceKey = isReverse ? 'lastTargetText' : 'lastSourceText';
    if (config[lastSourceKey] === text) {
      console.log('检测到相同内容，跳过翻译以防止循环');
      return;
    }
    
    // Determine source and target languages based on config and direction
    const sourceField = isReverse ? config.targetField : config.sourceField;
    const targetField = isReverse ? config.sourceField : config.targetField;
    
    console.log(`翻译请求(队列): ${sourceField} -> ${targetField}, 反向: ${isReverse}, 文本: ${text.substring(0, 30)}${text.length > 30 ? '...' : ''}, 索引: ${config.index}`);
    
    // Call the Baidu API with the target language field
    const translatedText = await callBaiduAPI(
      text, 
      config.index, 
      targetField
    );
    
    // 检查翻译结果是否与目标元素当前内容相同
    const currentTargetText = targetElement.innerText || targetElement.textContent || '';
    if (currentTargetText.trim() === translatedText) {
      console.log('翻译结果与当前内容相同，无需更新');
      return;
    }
    
    // 更新缓存
    if (isReverse) {
      config.lastTargetText = text;
      config.lastSourceText = translatedText as string;
    } else {
      config.lastSourceText = text;
      config.lastTargetText = translatedText as string;
    }
    
    // Update target element with translated text
    if (targetElement.isContentEditable) {
      targetElement.innerText = translatedText as string;
      // Trigger input event to update binding
      targetElement.dispatchEvent(new Event('input', { bubbles: true }));
    } else {
      // For non-contenteditable elements
      targetElement.textContent = translatedText as string;
    }
    
    console.log(`翻译完成(队列): ${sourceField} -> ${targetField}, 索引: ${config.index}`);
  } catch (error) {
    console.error('Translation error:', error);
    // Simple error notification
    alert('翻译失败，请稍后再试');
  }
}

// Initialize translation groups
export function initializeTranslationGroups() {
  // Define translation groups
  translationGroups.value = [
    {
      sourceField: 'english',
      targetField: 'chinese',
      sourceSelector: '.prompt-input',
      targetSelector: '.prompt-preview',
      index: 0,
      twoWay: true, // Enable two-way translation
      lastSourceText: '',
      lastTargetText: ''
    }
    // Add more groups as needed
  ];
  
  // Bind event listeners to each group
  translationGroups.value.forEach(config => {
    const sourceElement = document.querySelector(config.sourceSelector);
    const targetElement = document.querySelector(config.targetSelector);
    
    if (sourceElement && targetElement) {
      // Source to target translation
      sourceElement.addEventListener('input', () => {
        queueTranslation(config.index, false);
      });
      
      // If two-way translation is enabled, add reverse listener
      if (config.twoWay) {
        targetElement.addEventListener('input', () => {
          queueTranslation(config.index, true);
        });
      }
      
      console.log(`Translation group ${config.index} initialized`);
    } else {
      console.error('Could not find elements for translation group:', config);
    }
  });
}

// Export function to manually trigger translation
export function triggerTranslation(groupIndex: number, isReverse = false, delayMs = 1000) {
  queueTranslation(groupIndex, isReverse, delayMs);
}

// Add a new translation group
export function addTranslationGroup(config: TranslationGroupConfig) {
  // 确保新添加的组有缓存字段
  config.lastSourceText = '';
  config.lastTargetText = '';
  
  translationGroups.value.push(config);
  
  // Bind event listeners
  const sourceElement = document.querySelector(config.sourceSelector);
  const targetElement = document.querySelector(config.targetSelector);
  
  if (sourceElement && targetElement) {
    // Source to target translation
    sourceElement.addEventListener('input', () => {
      queueTranslation(config.index, false);
    });
    
    // If two-way translation is enabled, add reverse listener
    if (config.twoWay) {
      targetElement.addEventListener('input', () => {
        queueTranslation(config.index, true);
      });
    }
    
    console.log(`Translation group ${config.index} added`);
    console.log(`Translation group length ${translationGroups.value.length}`);
  } else {
    console.error('Could not find elements for new translation group:', config);
  }
} 